<?php
include_once 'includes/check_user.php';
$key = '';
if (isset($_REQUEST['key'])) $key = $_REQUEST['key'];
?>
<form name="search" method="get">
	<input id="search" name="key" type="text" value="<?php echo $key?>" size="80" placeholder="Enter key to search in Dict" />
	<input name="search" type="submit" value="Search" />
</form>
<hr />
<?php 
if (isset($_REQUEST['search'])) {
	include_once dirname(__FILE__) . '/mysql_connect.php';
	include_once dirname(__FILE__) . '/class.mydict.php';
	
	if (isset($_POST['update'])) {
		$update = $_POST['update'];
		$meaning = $_POST['meaning'];
		$note = $_POST['note'];
		if ($update == 'Add') {
			MyDict::addWord($key, $meaning, $note);
		} elseif ($update == 'Update') {
			MyDict::editWord($key, $meaning, $note);
		}
	}
	
	$row = MyDict::queryKey($key);?>
	<div class="form" style="width:73%;float:left">
		<form name="update" method="post">
		<?php
		$note = '';
		$meaning = '';
		$meaning_cat_names = array();
		$action = 'Add';
		if ($row) {
			$note = $row['note'];
			$meaning = $row['meaning'];
			$action = 'Update';
			$meaning_cats = MyDict::getMeaningCats($key);
			foreach ($meaning_cats as $cat) {
				$meaning_cat_names[] = $cat['name'];
			}
		}?>
			<input type="text" name="meaning" style="width:100%" value="<?php echo $meaning?>" /><br />
			<textarea id="note" name="note" style="width:100%" rows="20"><?php echo $note;?></textarea><br />
			<input type="submit" name="update" value="<?php echo $action;?>" />
		</form>
	</div>
	<div class="meta" style="float:left;margin-left:10px;width:25%">
		<h3>Meta</h3>
		meaning cat: <?php echo implode(', ', $meaning_cat_names)?> <a href="cat.php?key=<?php echo $key?>" target="_blank">edit</a>
	</div>
<?php }?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
	var cache = {};
	$("#search").autocomplete({
		minLength: 1,
		source: function( request, response ) {
			var term = request.term;
			if ( term in cache ) {
				response( cache[ term ] );
				return;
			}
			
			$.getJSON("includes/search.json.php?key=" + $("#search").val(), request, function(data, status, xhr) {
				cache[term] = data;
				response(data);
			});
		}
	});
});
</script>
<script type="text/javascript" src="js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
	tinyMCE.init({
		mode : "textareas",
		theme : "simple"
	});
</script>